package com.whately.core.base.keygen;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.math.BigInteger;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.concurrent.atomic.AtomicStampedReference;

/**
 * 时间戳单位是秒
 * 默认每秒产生 9999 个
 *
 * 2022年产生13位long，时间戳8+机器码1+随机数4
 * 2023年后到2050产生14位，时间戳为9+1+4
 * 2050年后15位
 */
@Slf4j
public class IdCreatorInSecond {
    private String machineCodeStr;

    private EnumGeneMaxNumberInTimeUnit every_second_max;

    // 带时间的序列，原子操作
    private AtomicStampedReference<StampedSequence> current;


    public IdCreatorInSecond(){
        this(EnumGeneMaxNumberInTimeUnit.max_9999);
    }


    public IdCreatorInSecond(EnumGeneMaxNumberInTimeUnit everySecondGenerateMaxNumbersEnum){
        this.current = StampedSequence.initRefer();
        this.every_second_max = everySecondGenerateMaxNumbersEnum==null? EnumGeneMaxNumberInTimeUnit.max_9999:everySecondGenerateMaxNumbersEnum;
        this.machineCodeStr = String.valueOf(WhatelyMachineCodeHelper.getMachineCode());
        log.info("IdCreatorEverySecond init finish ,machineCode {},every_second_max {} ", machineCodeStr,this.every_second_max);
    }


    public long nextId(){
        StampedSequence seq = StampedSequence.nextSequenceTimeInSecond(current,every_second_max.getMaxNumbers());
        long daySecondCountAfterEpoch = ChronoUnit.SECONDS.between( ConstantsIdGenerator.defaultEpoch20200101(),Instant.ofEpochSecond(seq.getTs()));
        return new BigInteger(daySecondCountAfterEpoch + machineCodeStr + StringUtils.leftPad(""+seq.getSequence(),every_second_max.getLens(),"0")).longValue();

    }


    public static void main(String[] args) {
        IdCreatorInSecond u = new IdCreatorInSecond();
        for(int i=0;i<10000;i++){
            System.out.println(u.nextId());
        }
    }


}
